<script setup>
/**
 * 核心聊天组件
 * 用于显示聊天内容
 */
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import ChatBox from './components/ChatMsgBox.vue'
import WebSocketService from '@/utils/ws.js'
import { useInChatContactInfStore } from '@/stores/useInChatContactInfStore.js'
import { getMessageAPI } from '@/api/messageAPI.js'

const inChatContactInfStore = useInChatContactInfStore()
const messageContainer = ref()
const messagesList = ref([])
const socketService = new WebSocketService()

// 监听 WebSocket 消息
const handleMessage = (msg) => {
    console.log(msg)
    messagesList.value.push(msg.content)
    nextTick(() => {
        if (messageContainer.value) {
            messageContainer.value.scrollTop = messageContainer.value.scrollHeight
        }
    })
}

const getMessageList = async (id) => {
    const res = await getMessageAPI(0, 100, id)
    if (res.data.code === 1) {
        messagesList.value = res.data.data
        console.log(res.data.data)
    } else {
        alert('获取聊天消息列表失败')
    }
}

watch(
    () => inChatContactInfStore.id, // 正在聊天的用户改变
    async (newValue) => {
        await getMessageList(newValue)
        await nextTick(() => {
            if (messageContainer.value) {
                messageContainer.value.scrollTop = messageContainer.value.scrollHeight
            }
        })
    },
)

onMounted(() => {
    socketService.connect()
    socketService.onMessage(handleMessage)
})

onUnmounted(() => {
    socketService.disconnect()
})
</script>

<template>
    <div style="padding: 17px; overflow-y: auto" ref="messageContainer" class="main">
        <ChatBox
            v-for="msg in messagesList"
            :key="msg"
            :fromUsername="msg.fromUsername"
            :toUsername="msg.toUsername"
            :message="msg.content"
            :createTime="msg.createTime"
            :type="msg.type"
            :imgSrc="inChatContactInfStore.headImgUrl"
        />
    </div>
</template>

<style scoped>
.main {
    height: 100%;
    overflow-y: auto;
    overflow-x: hidden;
    padding: 0 20px;
}
</style>
